// useZip.js
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
import { useExcel } from './useExcel';

export function useZip() {
    const { convertDataToExcel } = useExcel();

    // 将数组打包为Excle,zip格式并下载
    const createZipAndDownload = (data, zipName = 'data.zip') => {
        const zip = new JSZip();
        const excelData = convertDataToExcel(data);
        const s2ab = (s) => {
            const buf = new ArrayBuffer(s.length);
            const view = new Uint8Array(buf);
            for (let i = 0; i !== s.length; ++i) {
                view[i] = s.charCodeAt(i) & 0xFF;
            }
            return buf;
        };
        const arrayBuffer = s2ab(excelData);
        zip.file('data.xlsx', arrayBuffer, { binary: true });
        
        zip.generateAsync({ type: 'blob' }).then((content) => {
            saveAs(content, zipName);
        });
    };

    // 将数组打包为zip格式并下载
    function zipFiles(files, zipName = 'archive.zip') {
        const zip = new JSZip();

        files.forEach(file => {
            // 假设file对象包含name和content属性，content为字符串或Blob
            if (file.content instanceof Blob) {
                // 如果content是Blob对象，直接添加到zip中
                zip.file(file.name, file.content, { binary: true });
            } else {
                // 如果content是字符串，需要转换为Blob
                const blob = new Blob([file.content], { type: 'application/octet-stream' });
                zip.file(file.name, blob, { binary: true });
            }
        });

        // 生成zip文件并触发下载
        zip.generateAsync({ type: 'blob' }).then(content => {
            saveAs(content, zipName);
        });
    }

    return { createZipAndDownload, zipFiles };
}